package com.ldc.commonlibs.utils;

import android.app.Activity;
import android.app.Application;

import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import com.ldc.commonlibs.common.ViewModelBase;

/**
 * @author liudc
 * @since 2022/7/3 23:58
 */
public class ViewModelUtil {
    /**
     * @param application application
     * @param clazz       类
     * @param <T>         类型
     * @return ViewModel
     */
    public static <T extends ViewModelBase> T create(Application application, Class<T> clazz) {
        return ViewModelProvider.AndroidViewModelFactory
                .getInstance(application)
                .create(clazz);
    }

    /**
     * @param activity activity
     * @param clazz    类
     * @param <T>      类型
     * @return ViewModel
     */
    public static <T extends ViewModelBase> T create(Activity activity, Class<T> clazz) {
        return create(activity.getApplication(), clazz);

    }

    /**
     * @param fragment fragment
     * @param clazz    类
     * @param <T>      类型
     * @return ViewModel
     */
    public static <T extends ViewModelBase> T create(Fragment fragment, Class<T> clazz) {
        return create(fragment.requireActivity(), clazz);
    }
}
